package com.mxw.gateway.filter;

import com.mxw.gateway.config.GatewayAccessServiceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description TODO
 * @Author RingKo
 * @Date 2021/12/7 21:25
 * @Version 1.0
 */
@Component
@Order(0)
public class GatewayRequestFilter implements GlobalFilter {
  @Autowired
  private GatewayAccessServiceConfig gatewayAccessServiceConfig;

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    byte[] token = Base64Utils.encode((gatewayAccessServiceConfig.getGatewayTokenValue()).getBytes());
    String[] headerValues = {new String(token)};
    ServerHttpRequest build = exchange.getRequest()
        .mutate()
        .header(gatewayAccessServiceConfig.getGatewayTokenHeader(), headerValues)
        .build();

    ServerWebExchange newExchange = exchange.mutate().request(build).build();
    return chain.filter(newExchange);
  }

}